package com.gxnu.edu.cn.ttxxt.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gxnu.edu.cn.ttxxt.entity.FileTransfers;
import com.gxnu.edu.cn.ttxxt.entity.Messages;
import com.gxnu.edu.cn.ttxxt.entity.Users;
import com.gxnu.edu.cn.ttxxt.mapper.FileTransferRepository;
import com.gxnu.edu.cn.ttxxt.mapper.MessageRepository;
import com.gxnu.edu.cn.ttxxt.mapper.UserRepository;
import com.gxnu.edu.cn.ttxxt.service.FileService;
import com.gxnu.edu.cn.ttxxt.util.FileStorageUtil;
import com.gxnu.edu.cn.ttxxt.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

@Service
public class FileServiceIpml implements FileService {

    @Autowired
    private FileTransferRepository fileTransferRepository;

    @Autowired
    private MessageRepository messageRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private FileStorageUtil fileStorageUtil;

    @Override
    @Transactional
    public FileTransfers uploadFile(Long senderId, Long receiverId, MultipartFile file, boolean isGroup) throws IOException {
        // 验证用户存在
        Users sender = userRepository.selectById1(senderId);
        Users receiver = userRepository.selectById1(receiverId);
        if (sender == null || receiver == null) {
            throw new IllegalArgumentException("用户不存在");
        }

        // 存储文件
        String fileName = file.getOriginalFilename();
        String filePath = fileStorageUtil.storeFile(file);
        String fileMd5 = MD5Util.calculateMD5(file.getBytes());

        // 创建文件传输记录
        FileTransfers fileTransfers = new FileTransfers();
        fileTransfers.setSenderId(senderId);
        fileTransfers.setReceiverId(receiverId);
        fileTransfers.setFileName(fileName);
        fileTransfers.setFileSize(file.getSize());
        fileTransfers.setFilePath(filePath);
        fileTransfers.setFileMd5(fileMd5);
        fileTransfers.setIsGroup((int) (isGroup ? (byte) 1 : (byte) 0));
        fileTransfers.setStatus(1); // 传输中
        fileTransfers.setCreateTime(new Date());
        fileTransfers.setUpdateTime(new Date());

        fileTransferRepository.insert(fileTransfers);
        Messages messages = new Messages();
        messages.setSenderId(senderId);
        messages.setReceiverId(receiverId);
        messages.setStatus(1);
        messages.setMessageType(2);
        messages.setFileId(fileTransfers.getFileId());
        messages.setSendTime(new Date());
        messageRepository.insert(messages);
        System.out.println(fileTransfers.getFileId());
        return fileTransfers;
    }

    @Override
    public FileTransfers getFileById(Long fileId) {
        return fileTransferRepository.selectById1(fileId);
    }

    @Override
    public List<FileTransfers> getUserFiles(Long userId) {
        QueryWrapper<FileTransfers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sender_id", userId)
                .or()
                .eq("receiver_id", userId)
                .orderByDesc("create_time");

        return fileTransferRepository.selectList(queryWrapper);
    }

    @Override
    @Transactional
    public void startFileTransfer(Long fileId) {
        FileTransfers fileTransfers = fileTransferRepository.selectById(fileId);
        if (fileTransfers == null) {
            throw new IllegalArgumentException("文件记录不存在");
        }

        fileTransfers.setStatus(1); // 传输中
        fileTransfers.setUpdateTime(new Date());
        fileTransferRepository.updateById(fileTransfers);
    }

    @Override
    @Transactional
    public void completeFileTransfer(Long fileId) {
        FileTransfers fileTransfers = fileTransferRepository.selectById(fileId);
        if (fileTransfers == null) {
            throw new IllegalArgumentException("文件记录不存在");
        }

        fileTransfers.setStatus(2); // 已完成
        fileTransfers.setUpdateTime(new Date());
        fileTransferRepository.updateById(fileTransfers);
    }

    @Override
    @Transactional
    public void cancelFileTransfer(Long fileId) {
        FileTransfers fileTransfers = fileTransferRepository.selectById(fileId);
        if (fileTransfers == null) {
            throw new IllegalArgumentException("文件记录不存在");
        }

        fileTransfers.setStatus(3); // 已取消
        fileTransfers.setUpdateTime(new Date());
        fileTransferRepository.updateById(fileTransfers);

        // 删除已上传的文件
        try {
            Files.deleteIfExists(Paths.get(fileTransfers.getFilePath()));
        } catch (IOException e) {
            throw new RuntimeException("删除文件失败", e);
        }
    }

    @Override
    @Transactional
    public void failFileTransfer(Long fileId, String reason) {
        FileTransfers fileTransfers = fileTransferRepository.selectById(fileId);
        if (fileTransfers == null) {
            throw new IllegalArgumentException("文件记录不存在");
        }

        fileTransfers.setStatus( 4); // 已失败
        fileTransfers.setUpdateTime(new Date());
        fileTransferRepository.updateById(fileTransfers);

        // 删除已上传的文件
        try {
            Files.deleteIfExists(Paths.get(fileTransfers.getFilePath()));
        } catch (IOException e) {
            throw new RuntimeException("删除文件失败", e);
        }
    }

    @Override
    public byte[] downloadFile(Long fileId) throws IOException {
        FileTransfers fileTransfers = fileTransferRepository.selectById(fileId);
        if (fileTransfers == null) {
            throw new IllegalArgumentException("文件记录不存在");
        }

        if (fileTransfers.getStatus() != 2) { // 只有已完成状态的文件可以下载
            throw new IllegalStateException("文件不可下载，当前状态: " + fileTransfers.getStatus());
        }

        Path path = Paths.get(fileTransfers.getFilePath());
        return Files.readAllBytes(path);
    }
}